package net.maergaiyun.controller;

import lombok.extern.slf4j.Slf4j;
import net.maergaiyun.enums.ShortLinkStateEnum;
import net.maergaiyun.model.ShortLinkDO;
import net.maergaiyun.service.LinkGroupService;
import net.maergaiyun.service.LogService;
import net.maergaiyun.service.ShortLinkService;
import net.maergaiyun.util.CommonUtil;
import net.maergaiyun.vo.ShortLinkVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@Slf4j
public class LinkApiController {
    @Autowired
    private ShortLinkService shortLinkService;

    @Autowired
    private LogService logService;

    /**
     * 301永久重定向, 302临时重定向
     * 短地址生成之后不会变化, 301对服务器压力减少, 如果使用301无法统计短地址被点击次数
     * 选择302可以获取到很多数据进行分析
     *
     * @param shortLinkCode
     * @param request
     * @param response
     */
    @GetMapping(path = "/{shortLinkCode}")
    public void dispatch(@PathVariable(name = "shortLinkCode") String shortLinkCode, HttpServletRequest request, HttpServletResponse response) {
        log.info("短链码: {}", shortLinkCode);
        try {

            if (isLetterDigit(shortLinkCode)) {
                // 查找短链
                ShortLinkVO shortLinkVO = shortLinkService.parseShortLinkCode(shortLinkCode);

                logService.recordShortLinkLog(request, shortLinkCode, shortLinkVO.getAccountNo());

                if (isVisitable(shortLinkVO)) {
                    String originUrl = CommonUtil.removeUrlPrefix(shortLinkVO.getOriginalUrl());

                    response.setHeader("Location", originUrl);
                    response.setStatus(HttpStatus.FOUND.value());
                } else {
                    response.setStatus(HttpStatus.NOT_FOUND.value());
                }
            }
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }

    }

    /**
     * 1980-01-01
     */
    private static final long FOREVER_TIME = 315504000000L;

    /**
     * 检验短链码是否过期
     *
     * @param shortLinkVO
     * @return
     */
    public static boolean isVisitable(ShortLinkVO shortLinkVO) {
        if (shortLinkVO != null && shortLinkVO.getExpired().getTime() > CommonUtil.getCurrentTimestamp()) {
            if (ShortLinkStateEnum.ACTIVE.name().equalsIgnoreCase(shortLinkVO.getState())) {
                return true;

            }
        } else if (shortLinkVO != null && shortLinkVO.getExpired().getTime() < FOREVER_TIME) {
            if (ShortLinkStateEnum.ACTIVE.name().equalsIgnoreCase(shortLinkVO.getState())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 校验短链码是否是数字和字符组成
     *
     * @param code
     * @return
     */
    public static boolean isLetterDigit(String code) {
        String regex = "^[a-z0-9A-Z]+$";
        return code.matches(regex);
    }
}
